package xyz.gpgl.erp.logic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import common.util.base.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import xyz.gpgl.erp.logic.entity.LogicShares;
import xyz.gpgl.erp.logic.entity.LogicSharesXpathDetail;
import xyz.gpgl.erp.logic.entity.LogicSharesXpathMaster;
import xyz.gpgl.erp.logic.entity.emeus.LogicSharesEmeus;
import xyz.gpgl.erp.logic.entity.emeus.LogicSharesXpathDetailEmeus;
import xyz.gpgl.erp.logic.service.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liubo
 * @created 2019-11-06 16:26
 */
@Slf4j
@Service
public class SharesTaskServiceImpl implements ISharesTaskService {

    private static final String CODE = "%code";
    private static final String LOCATION = "%s";

    @Autowired
    private IEmailService mailService;
    @Autowired
    private ILogicSharesService logicSharesService;


    @Async
    @Override
    public void monitorStockChanges(LogicShares share ,LogicSharesXpathMaster  xpath,Map<String, LogicSharesXpathDetail> xpathMap) {
        log.info("监视股票变化->数据抓去开始");
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        //当JS执行出错的时候是否抛出异常
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        //当HTTP的状态非200时是否抛出异常
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setActiveXNative(false);
        //是否启用CSS
        webClient.getOptions().setCssEnabled(false);
        //很重要，启用JS
        webClient.getOptions().setJavaScriptEnabled(true);
        //很重要，设置支持AJAX
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        //设置“浏览器”的请求超时时间
        webClient.getOptions().setTimeout(50000);
        //设置JS执行的超时时间
        webClient.setJavaScriptTimeout(20000);
        try {
            log.info("监视股票变化->开始获取{}[{}]信息",share.getName(),share.getCode());
            //组装URL
            String url = xpath.getUrl().replace(CODE,  share.getCode()).replace(LOCATION,
                    LogicSharesEmeus.StockExchange.shangzheng.equals(share.getStockExchange())?xpath.getSh():xpath.getSz());
            HtmlPage page = webClient.getPage(url);
            UpdateWrapper<LogicShares> updateWrapper = new UpdateWrapper<>();
            for (String key : xpathMap.keySet()) {
                LogicSharesXpathDetail currentPriceXpath = xpathMap.get(key);
                BigDecimal value = new BigDecimal(this.getStringValueByXPath(page, currentPriceXpath));
                updateWrapper.set(CommonUtil.dbHumpToDB(key),value);
            }
            updateWrapper.eq(LogicSharesEmeus.id, share.getId());
            this.logicSharesService.update(updateWrapper);
        } catch (Exception e) {
            log.error("获取页面失败" , e);
        }finally {
            webClient.close();
        }
    }



    private String getStringValueByXPath(HtmlPage page, LogicSharesXpathDetail debtRatioXpath) {
        String debtRatio = ((DomElement) page.getByXPath(debtRatioXpath.getXpath()).get(debtRatioXpath.getSerialNumber()-1)).asText();
        if (CommonUtil.isNotEmpty(debtRatioXpath.getRegex())) {
            Pattern pattern = Pattern.compile(debtRatioXpath.getRegex());
            Matcher matcher = pattern.matcher(debtRatio);
            if (matcher.find()) {
                debtRatio = matcher.group(0);
            }
        }
        return debtRatio;
    }


}
